package cn.bookCity.serviceimpl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;

import org.apache.commons.dbutils.handlers.BeanHandler;


import cn.bookCity.Exception.MyException;
import cn.bookCity.dao.UserDao;
import cn.bookCity.domain.User;
import cn.bookCity.service.UserService;
import cn.bookCity.util.BeanFactory;
import cn.bookCity.util.MailUtils;

public class UserServiceImpl implements UserService {

	@Override
	public void regist(User user) throws MyException {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		User u=userDao.selectUserByEamil(user.getEmail());
		if(u!=null)throw new MyException("您已经注册了，请直接登录");
		userDao.regist(user);
		String message="欢迎您注册成我们的一员,<a href='http://localhost:8080/bookCity/book/user?method=active&code="+user.getActiveCode()+"'>点此激活</a>";
		try {
			MailUtils.sendMail(user.getEmail(), message);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void active(String code) throws MyException {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		User user=userDao.selectUserByCode(code);
		if(user==null)throw new MyException("激活码无效！");
		if(user.getState()==1)throw new MyException("您已经激活了，请不要再试了！");
		user.setState(1);
		userDao.UpdateUserByUser(user);
		
	}

	@Override
	public User login(String username, String password) {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		return userDao.selectUserByNP(username, password);
	}

	@Override
	public User checkUser(String username) {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		return userDao.selectUserName(username);
	}

	@Override
	public User checkEmail(String email) {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		return userDao.selectUserByEamil(email);
	}

	@Override
	public List<User> get() {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		return userDao.get();
	}

	@Override
	public void del(String uid) {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		userDao.del(uid);
		
	}

	@Override
	public User findUserByNameAndPwd(String username, String password) {
		UserDao userDao=(UserDao)BeanFactory.getBean("UserDao");
		
		return userDao.selectUserByNP(username,password);
	}
}
